from flask import Flask as _Flask,jsonify
from flask import request
from flask import render_template
from flask.json import JSONEncoder as _JSONEncoder
from flask import send_file, make_response  
from jieba.analyse import extract_tags
from lib.upload import file_upload,excelData
import pymongo
import lib.mongodb
import lib.explode
# import lib.explode
import datetime
import json
import math
import urllib.parse
import lib.bzh
import lib.pollutant
import lib.handle
from flask import send_from_directory

# from lib.mongodb import excel_import,insertDBname,getList
class JSONEncoder(_JSONEncoder):
        def default(self, o):
            if isinstance(o, decimal.Decimal):
                return float(o)
            super(_JSONEncoder, self).default(o)

class Flask(_Flask):
    json_encoder = JSONEncoder

app = Flask(__name__)

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/welcome')
def welcome():
    return render_template("welcome.html")

@app.route('/data')  #监测数据组
def data():
    return render_template("data.html")

@app.route('/data_add')  #监测数据组
def data_add():
    return render_template("data_add.html")

@app.route('/data_post',methods=['POST', 'GET'])  #上传提交
def data_post():
    title = request.form.get('title')
    file = request.files['files']
    file_path = file_upload(file)
    if(file_path == ''):
        return '上传失败,请上传后缀为 xls,xlsx,csv 的文件<script>setTimeout(function(){history.go(-1)},1500)</script>'
    # lib.mongodb.insertDBname(title)
    lib.mongodb.excel_import2('./'+file_path,title)  #导入数据

    return "<script>alert('上传成功');var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);parent.location.reload();  </script>"

@app.route('/getList',methods=['POST', 'GET']) #获取数据列表
def getList():
    dataList = lib.mongodb.getList()
    return jsonify(dataList)

@app.route('/echarts/<title>',methods=['POST', 'GET'])
def echarts(title):
    # return render_template("echarts.html",title=title)
    # title=urllib.parse.unquote(title)
    jsonD = lib.mongodb.getAvgData(title)
    sheetList = jsonD['sheetList']
    dataList = json.dumps(jsonD['dataList'])
    # dataList = jsonify(jsonD['dataList'])
    return render_template("echarts.html",dataList=dataList,dataList2=jsonD['dataList'],sheetList=sheetList,sheetList2=json.dumps(sheetList),title=title)

@app.route('/data_list/<title>/<name>/<month>/<page>',methods=['POST', 'GET'])
def data_list(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    data_list = lib.mongodb.selectAll(title,name,month)
    sheetList = data_list['sheetList']
    data = data_list['returndata']
    total = len(data)
    totalpage = math.ceil(total/30)
    data = data[start:start+limit]
    for i in data:
        i['AQI'] = '%.4f' % i['AQI']
        i['dayPM25'] = '%.4f' % i['dayPM25']
        i['daySO2'] = '%.4f' % i['daySO2']
        i['dayNO'] = '%.4f' % i['dayNO']
        i['dayNO2'] = '%.4f' % i['dayNO2']
        i['dayNOx'] = '%.4f' % i['dayNOx']
        i['dayO3'] = '%.4f' % i['dayO3']
        i['dayCO'] = '%.4f' % i['dayCO']
        i['dayPM10'] = '%.4f' % i['dayPM10']
    if(month != '0'):
        month2 = month.split('_')
        start_time = month2[0]
        end_time = month2[1]
        start_time = start_time.split('-')
        end_time = end_time.split('-')
        date = {'year1':int(start_time[0]),'month1':int(start_time[1]),'day1':int(start_time[2]),'year2':int(end_time[0]),'month2':int(end_time[1]),'day2':int(end_time[2])}
    else:
        date = {'year1':'','month1':'','day1':'','year2':'','month2':'','day2':''}
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage}
    return render_template("data_list.html",sheetList=sheetList,date=date,data=data,args=args)

@app.route('/data_list_charts/<title>/<name>/<month>/<types>')
def data_list_charts(title,name,month,types):
    data_list = lib.mongodb.getSearch(title,name,month)
    sheetList = data_list['sheetList']
    data = data_list['data']
    jsondata = json.dumps(data)
    monthList = data_list['monthList']
    typesList = data_list['typesList']
    args = {'title':title,'name':name,"month":int(month),"type":types}
    return render_template("data_list_charts.html",sheetList=sheetList,data=jsondata,args=args,typesList=typesList,monthList=monthList)

@app.route('/details/<title>/<name>',methods=['POST', 'GET'])
def details(title,name):
    details = lib.mongodb.getDetails(title,name)
    if details['code'] == -1:
        return details['msg']+'...<a href="/echarts/'+title+'">点击返回</a>'
    details2 = json.dumps(details['data'])
    title = ['温度','风向','风速','湿度','气压']
    return render_template('details.html',details = details['data'],details2 = details2,title=title)

@app.route('/data_del/<title>',methods = ['POST', 'GET'])
def data_del(title):
    lib.mongodb.delete(title)
    return jsonify({'code':1,"msg":"删除成功"})


@app.route('/echarts_data',methods=['POST', 'GET'])
def echarts_data():  #各个平均值
    title = request.form.get('id')
    title=urllib.parse.unquote(title)
    json = lib.mongodb.getAvgData(title)
    # return title
    return jsonify(json)

@app.route('/biaozhun_01/<title>/<name>/<month>/<page>',methods=['POST', 'GET'])
def biaozhun(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)
    if name == '0':
        name = sheetList[0]
    if month == 0:
        month = 1
    data_list = lib.mongodb.selectAll(title,name,month)
    with open('./test_text.txt','w') as file_object:
        file_object.write(str(data_list))
    # sheetList = data_list['sheetList']
    data = data_list['returndata']
    total = len(data)
    totalpage = math.ceil(total/30)
    data = data[start:start+limit]
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Min_MaxNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Min_MaxNorm()
    co = lib.bzh.Datanorm(dayCO).Min_MaxNorm()
    no = lib.bzh.Datanorm(dayNO).Min_MaxNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Min_MaxNorm()
    o3 = lib.bzh.Datanorm(dayO3).Min_MaxNorm()
    so2 = lib.bzh.Datanorm(daySO2).Min_MaxNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Min_MaxNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage,'title':title,'name':name}
    return render_template('biaozhun_01.html',titleList=titleList,sheetList=sheetList,data=data,args=args)

@app.route('/score/<title>/<name>/<month>/<page>',methods=['POST', 'GET'])
def score(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)
    if name == '0':
        name = sheetList[0]
    if month == 0:
        month = 1
    data_list = lib.mongodb.selectAll(title,name,month)
    # sheetList = data_list['sheetList']
    data = data_list['returndata']
    total = len(data)
    totalpage = math.ceil(total/30)
    data = data[start:start+limit]
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Z_ScoreNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Z_ScoreNorm()
    co = lib.bzh.Datanorm(dayCO).Z_ScoreNorm()
    no = lib.bzh.Datanorm(dayNO).Z_ScoreNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Z_ScoreNorm()
    o3 = lib.bzh.Datanorm(dayO3).Z_ScoreNorm()
    so2 = lib.bzh.Datanorm(daySO2).Z_ScoreNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Z_ScoreNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage,'title':title,'name':name}
    return render_template('score.html',titleList=titleList,sheetList=sheetList,data=data,args=args)
@app.route('/scaling/<title>/<name>/<month>/<page>',methods=['POST', 'GET'])
def scaling(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)
    if name == '0':
        name = sheetList[0]
    if month == 0:
        month = 1
    data_list = lib.mongodb.selectAll(title,name,month)
    # sheetList = data_list['sheetList']
    data = data_list['returndata']
    total = len(data)
    totalpage = math.ceil(total/30)
    data = data[start:start+limit]
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Decimal_ScalingNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Decimal_ScalingNorm()
    co = lib.bzh.Datanorm(dayCO).Decimal_ScalingNorm()
    no = lib.bzh.Datanorm(dayNO).Decimal_ScalingNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Decimal_ScalingNorm()
    o3 = lib.bzh.Datanorm(dayO3).Decimal_ScalingNorm()
    so2 = lib.bzh.Datanorm(daySO2).Decimal_ScalingNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Decimal_ScalingNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage,'title':title,'name':name}
    return render_template('scaling.html',titleList=titleList,sheetList=sheetList,data=data,args=args)
@app.route('/normalization/<title>/<name>/<month>/<page>',methods=['POST', 'GET'])
def normalization(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)
    if name == '0':
        name = sheetList[0]
    if month == 0:
        month = 1
    data_list = lib.mongodb.selectAll(title,name,month)
    # sheetList = data_list['sheetList']
    data = data_list['returndata']
    total = len(data)
    totalpage = math.ceil(total/30)
    data = data[start:start+limit]
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).MeanNorm()
    aqi = lib.bzh.Datanorm(dayAQI).MeanNorm()
    co = lib.bzh.Datanorm(dayCO).MeanNorm()
    no = lib.bzh.Datanorm(dayNO).MeanNorm()
    no2 = lib.bzh.Datanorm(dayNO2).MeanNorm()
    o3 = lib.bzh.Datanorm(dayO3).MeanNorm()
    so2 = lib.bzh.Datanorm(daySO2).MeanNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).MeanNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage,'title':title,'name':name}
    return render_template('normalization.html',titleList=titleList,sheetList=sheetList,data=data,args=args)

@app.route('/data_explode/<title>/<name>/<month>',methods=['POST', 'GET'])
def data_explode(title,name,month):
    data_list = lib.mongodb.selectAll(title,name,month)
    data = data_list['returndata']
    with open('./test_text.txt','w') as file_object:
        file_object.write(str(data))
    dataset = []
    for i in data:
        d = [i['date'],i['title'],i['AQI'],i['dayPM25'],i['daySO2'],i['dayNO'],i['dayNO2'],i['dayNOx'],i['dayO3'],i['dayCO'],i['dayPM10']]
        dataset.append(d)
    headers = ['时间','地区','AQI','PM2.5 μg/m3','SO2 μg/m3','NO μg/m3','NO2 μg/m3','NOx μg/m3','O3 μg/m3','CO μg/m3','PM10 μg/m3']
    url = lib.explode.explode(headers,dataset)
    return jsonify({'code':10001,'url':url})

@app.route('/data_explode_bz01/<title>/<name>/<month>',methods=['POST', 'GET'])
def data_explode_bz01(title,name,month):
    data_list = lib.mongodb.selectAll(title,name,month)
    data = data_list['returndata']
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Min_MaxNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Min_MaxNorm()
    co = lib.bzh.Datanorm(dayCO).Min_MaxNorm()
    no = lib.bzh.Datanorm(dayNO).Min_MaxNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Min_MaxNorm()
    o3 = lib.bzh.Datanorm(dayO3).Min_MaxNorm()
    so2 = lib.bzh.Datanorm(daySO2).Min_MaxNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Min_MaxNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    dataset = []
    for i in data:
        d = [i['date'],i['title'],'0-1标准化',i['AQI'],i['dayPM25'],i['daySO2'],i['dayNO'],i['dayNO2'],i['dayNOx'],i['dayO3'],i['dayCO'],i['dayPM10']]
        dataset.append(d)
    headers = ['时间','地区','标准化方式','AQI','PM2.5 μg/m3','SO2 μg/m3','NO μg/m3','NO2 μg/m3','NOx μg/m3','O3 μg/m3','CO μg/m3','PM10 μg/m3']
    url = lib.explode.explode(headers,dataset)
    return jsonify({'code':10001,'url':url})

@app.route('/score_exp/<title>/<name>/<month>',methods=['POST', 'GET'])
def score_exp(title,name,month):
    data_list = lib.mongodb.selectAll(title,name,month)
    data = data_list['returndata']
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Min_MaxNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Min_MaxNorm()
    co = lib.bzh.Datanorm(dayCO).Min_MaxNorm()
    no = lib.bzh.Datanorm(dayNO).Min_MaxNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Min_MaxNorm()
    o3 = lib.bzh.Datanorm(dayO3).Min_MaxNorm()
    so2 = lib.bzh.Datanorm(daySO2).Min_MaxNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Min_MaxNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    dataset = []
    for i in data:
        d = [i['date'],i['title'],'Z-Score标准化',i['AQI'],i['dayPM25'],i['daySO2'],i['dayNO'],i['dayNO2'],i['dayNOx'],i['dayO3'],i['dayCO'],i['dayPM10']]
        dataset.append(d)
    headers = ['时间','地区','标准化方式','AQI','PM2.5 μg/m3','SO2 μg/m3','NO μg/m3','NO2 μg/m3','NOx μg/m3','O3 μg/m3','CO μg/m3','PM10 μg/m3']
    url = lib.explode.explode(headers,dataset)
    return jsonify({'code':10001,'url':url})
@app.route('/scaling_exp/<title>/<name>/<month>',methods=['POST', 'GET'])
def scaling_exp(title,name,month):
    data_list = lib.mongodb.selectAll(title,name,month)
    data = data_list['returndata']
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Min_MaxNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Min_MaxNorm()
    co = lib.bzh.Datanorm(dayCO).Min_MaxNorm()
    no = lib.bzh.Datanorm(dayNO).Min_MaxNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Min_MaxNorm()
    o3 = lib.bzh.Datanorm(dayO3).Min_MaxNorm()
    so2 = lib.bzh.Datanorm(daySO2).Min_MaxNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Min_MaxNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    dataset = []
    for i in data:
        d = [i['date'],i['title'],'小数定标标准化',i['AQI'],i['dayPM25'],i['daySO2'],i['dayNO'],i['dayNO2'],i['dayNOx'],i['dayO3'],i['dayCO'],i['dayPM10']]
        dataset.append(d)
    headers = ['时间','地区','标准化方式','AQI','PM2.5 μg/m3','SO2 μg/m3','NO μg/m3','NO2 μg/m3','NOx μg/m3','O3 μg/m3','CO μg/m3','PM10 μg/m3']
    url = lib.explode.explode(headers,dataset)
    return jsonify({'code':10001,'url':url})
@app.route('/normalization_exp/<title>/<name>/<month>',methods=['POST', 'GET'])
def normalization_exp(title,name,month):
    data_list = lib.mongodb.selectAll(title,name,month)
    data = data_list['returndata']
    dataPM25,dayAQI,dayPM10,dayNO,daySO2,dayCO,dayNO2,dayO3 = [],[],[],[],[],[],[],[]
    for i in data:
        dataPM25.append(i['dayPM25'])
        dayPM10.append(i['dayPM10'])
        dayAQI.append(i['AQI'])
        daySO2.append(i['daySO2'])
        dayCO.append(i['dayCO'])
        dayNO.append(i['dayNO'])
        dayNO2.append(i['dayNO2'])
        dayO3.append(i['dayO3'])
    pm25 = lib.bzh.Datanorm(dataPM25).Min_MaxNorm()
    aqi = lib.bzh.Datanorm(dayAQI).Min_MaxNorm()
    co = lib.bzh.Datanorm(dayCO).Min_MaxNorm()
    no = lib.bzh.Datanorm(dayNO).Min_MaxNorm()
    no2 = lib.bzh.Datanorm(dayNO2).Min_MaxNorm()
    o3 = lib.bzh.Datanorm(dayO3).Min_MaxNorm()
    so2 = lib.bzh.Datanorm(daySO2).Min_MaxNorm()
    pm10 = lib.bzh.Datanorm(dayPM10).Min_MaxNorm()
    for i in range(0,len(pm25)):
        data[i]['dayPM25'] = '%.4f' % pm25[i]
    for i in range(0,len(aqi)):
        data[i]['AQI'] = '%.4f' % aqi[i]
    for i in range(0,len(co)):
        data[i]['dayCO'] = '%.4f' % co[i]
    for i in range(0,len(no)):
        data[i]['dayNO'] = '%.4f' % no[i]
    for i in range(0,len(no2)):
        data[i]['dayNO2'] = '%.4f' % no2[i]
    for i in range(0,len(o3)):
        data[i]['dayO3'] = '%.4f' % o3[i]
    for i in range(0,len(so2)):
        data[i]['daySO2'] = '%.4f' % so2[i]
    for i in range(0,len(pm10)):
        data[i]['dayPM10'] = '%.4f' % pm10[i]
    dataset = []
    for i in data:
        d = [i['date'],i['title'],'均值归一法',i['AQI'],i['dayPM25'],i['daySO2'],i['dayNO'],i['dayNO2'],i['dayNOx'],i['dayO3'],i['dayCO'],i['dayPM10']]
        dataset.append(d)
    headers = ['时间','地区','标准化方式','AQI','PM2.5 μg/m3','SO2 μg/m3','NO μg/m3','NO2 μg/m3','NOx μg/m3','O3 μg/m3','CO μg/m3','PM10 μg/m3']
    url = lib.explode.explode(headers,dataset)
    return jsonify({'code':10001,'url':url})

@app.route('/get_attachment/<path:filename>')
def get_attachment(filename):
    return send_from_directory('./explode',filename,as_attachment=True)


@app.route('/pollutant/<title>/<name>/<month>/<page>')
def pollutant(title,name,month,page):
    page = int(page)
    limit = 10
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)
    if name == '0':
        name = sheetList[0]
    data_list = lib.pollutant.getPollutant(title,name,month)
    data_list = data_list['returndata']
    total = len(data_list)
    totalpage = math.ceil(total/limit)
    data = data_list[start:start+limit]
    if(month != '0'):
        month2 = month.split('_')
        start_time = month2[0]
        end_time = month2[1]
        start_time = start_time.split('-')
        end_time = end_time.split('-')
        date = {'year1':int(start_time[0]),'month1':int(start_time[1]),'day1':int(start_time[2]),'year2':int(end_time[0]),'month2':int(end_time[1]),'day2':int(end_time[2])}
    else:
        date = {'year1':'','month1':'','day1':'','year2':'','month2':'','day2':''}
    args = {'title':title,'name':name,'month':month,'totalpage':totalpage,'page':page}
    return render_template('pollutant.html',args=args,titleList=titleList,sheetList=sheetList,date=date,data=data)

@app.route('/census/<title>/<name>/<month>')
def census(title,name,month):
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)
    if name == '0':
        name = sheetList[0]
    if month == '0':
        month = 1
    dataList = lib.pollutant.getBT(title,name,month)
    monthList = dataList['monthList']
    data = dataList['data']
    datajson = json.dumps(data)
    args = {'title':title,'name':name,'month':int(month)}
    return render_template('census.html',args=args,titleList=titleList,sheetList=sheetList,data=data,datajson=datajson,monthList=monthList)

@app.route('/data_hours/<title>/<name>/<month>/<page>',methods=['POST', 'GET'])
def data_hours(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)

    if name == '0':
        name = sheetList[0]
    data = lib.mongodb.data_hours(title,name,month)
    total = len(data)
    totalpage = math.ceil(total/limit)
    data = data[start:start+limit]
    for i in data:
        if i['so2']:
            i['so2'] = '%.4f' % i['so2']
        else:
            i['so2'] = ''
        if i['aqi']:
            i['aqi'] = '%.4f' % i['aqi']
        else:
            i['aqi'] = ''
        if i['pm25']:
            i['pm25'] = '%.4f' % i['pm25']
        else:
            i['pm25'] = ''
        if i['no']:
            i['no'] = '%.4f' % i['no']
        else:
            i['no'] = ''
        if i['no2']:
            i['no2'] = '%.4f' % i['no2']
        else:
            i['no2'] = ''
        if i['nox']:
            i['nox'] = '%.4f' % i['nox']
        else:
            i['nox'] = ''
        if i['o3']:
            i['o3'] = '%.4f' % i['o3']
        else:
            i['o3'] = ''
        if i['co']:
            i['co'] = '%.4f' % i['co']
        else:
            i['co'] = ''
        if i['pm10']:
            i['pm10'] = '%.4f' % i['pm10']
        else:
            i['pm10'] = ''
    if(month != '0'):
        month2 = month.split('_')
        start_time = month2[0]
        end_time = month2[1]
        start_time = start_time.split('-')
        end_time = end_time.split('-')
        date = {'year1':int(start_time[0]),'month1':int(start_time[1]),'day1':int(start_time[2]),'year2':int(end_time[0]),'month2':int(end_time[1]),'day2':int(end_time[2])}
    else:
        date = {'year1':'','month1':'','day1':'','year2':'','month2':'','day2':''}
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage} #
    # data = []
    return render_template("data_hours.html",sheetList=sheetList,titleList=titleList,date=date,data=data,args=args)

@app.route('/data_explode_hours/<title>/<name>/<month>',methods=['POST', 'GET'])
def data_explode_hours(title,name,month):
    data = lib.mongodb.data_hours(title,name,month)
    # with open('./test_text.txt','w') as file_object:
    #     file_object.write(str(data))
    dataset = []
    for i in data:
        d = [i['time'],name,i['aqi'],i['pm25'],i['so2'],i['no'],i['no2'],i['nox'],i['o3'],i['co'],i['pm10']]
        dataset.append(d)
    headers = ['时间','地区','AQI','PM2.5 μg/m3','SO2 μg/m3','NO μg/m3','NO2 μg/m3','NOx μg/m3','O3 μg/m3','CO μg/m3','PM10 μg/m3']
    url = lib.explode.explode(headers,dataset)
    return jsonify({'code':10001,'url':url})
@app.route('/excel_change',methods=['POST','GET'])
def excel_change():
    return render_template('excel_change.html')

@app.route('/excel_exchange_post',methods=['POST','GET'])
def excel_exchange_post():
    file = request.files['files']
    # return str(file.filename)
    file_path = lib.upload.file_upload2(file)
    if(file_path == ''):
        return '上传失败,请上传后缀为 xls,xlsx,csv 的文件<script>setTimeout(function(){history.go(-1)},1500)</script>'
    file_path = file_path.replace('upload\\','')
    
    ext = file.filename.rsplit('.', 1)[1]
    if ext == 'xls':
        lib.explode.exchange(file_path)
        downloadURL = './upload/'+file_path.replace('.xls','.xlsx')
        filename = file_path.replace('.xls','.xlsx')
        response = make_response(send_file(downloadURL))
        response.headers["Content-Disposition"] = "attachment; filename={};".format(filename)
        return response
    elif ext == 'xlsx':
        lib.explode.exchange2(file_path)
        downloadURL = './upload/'+file_path.replace('.xlsx','.xls')
        filename = file_path.replace('.xlsx','.xls')
        response = make_response(send_file(downloadURL))
        response.headers["Content-Disposition"] = "attachment; filename={};".format(filename)
        return response
    elif ext == 'csv':
        lib.explode.exchange3(file_path)
        downloadURL = './upload/'+file_path.replace('.csv','.xlsx')
        filename = file_path.replace('.csv','.xlsx')
        response = make_response(send_file(downloadURL))
        response.headers["Content-Disposition"] = "attachment; filename={};".format(filename)
        return response

    return downloadURL
    # return downloadURL
    return render_template(downloadURL)
@app.route('/queshi/<title>/<name>/<month>/<page>',methods=['POST','GET'])
def queshi(title,name,month,page):
    page = int(page)
    limit = 30
    start = (page-1)*limit
    titleList = lib.mongodb.getTitle()
    if title=='0':
        title = titleList[0]
    sheetList = lib.mongodb.getSheetList(title)

    if name == '0':
        name = sheetList[0]
    if(month != '0'):
        month2 = month.split('_')
        start_time = month2[0]
        end_time = month2[1]
        start_time = start_time.split('-')
        end_time = end_time.split('-')
        date = {'year1':int(start_time[0]),'month1':int(start_time[1]),'day1':int(start_time[2]),'year2':int(end_time[0]),'month2':int(end_time[1]),'day2':int(end_time[2])}
    else:
        date = {'year1':'','month1':'','day1':'','year2':'','month2':'','day2':''}
    data = lib.mongodb.data_hours(title,name,month)
    total = len(data)
    data = data[start:start+limit]
    totalpage = math.ceil(total/limit)
    args = {'title':title,'name':name,"page":int(page),'month':month,"total":total,"totalpage":totalpage} #
    return render_template('/queshi.html',sheetList=sheetList,titleList=titleList,date=date,data=data,args=args)
@app.route('/queshi_handle/<title>/<name>/<month>/<page>',methods=['POST','GET'])
def queshi_handle(title,name,month,page):
    # page = int(page)
    # limit = 30
    # start = (page-1)*limit
    data = lib.mongodb.data_hours(title,name,month)
    handle_data = lib.handle.handle_queshi(data)
    res = lib.handle.update(title,name,handle_data)
    if res:
        return jsonify({'code':10001,'msg':'处理完成'})

    



if __name__ == '__main__':
    # lib.mongodb.excel_import2('./upload/ce83fcec-3fa2-492b-b705-b54b0be49ce6.xls','测试')
    # exit()
    # lib.mongodb.data_hours('122222','铁路设计院',"2015-01-01_2015-01-03",1)
    # exit()
    # data_list = lib.mongodb.selectAll('123','铁路设计院','0')
    # with open('./test_text.txt','w') as file_object:
    #     file_object.write(str(data_list))
    # data = data_list['returndata']
    # dataPM25 = []
    # for i in data:
    #     dataPM25.append(i['dayPM25'])
    # a = lib.bzh.Datanorm(dataPM25)
    # b = a.Min_MaxNorm()
    # data_list = lib.mongodb.getSearch('123','铁路设计院',"1")
    # print(b)
    # exit()
    # titleList = lib.mongodb.getTitle()
    # title = 0
    # if title==0:
    #     title = titleList[0]
    # sheetList = lib.mongodb.getSheetList(title)
    # print(sheetList)
    # lib.pollutant.getBT('123','铁路设计院',1)
    app.run(host="127.0.0.1",port=5000,debug=True)
